package cn.stylefeng.guns.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.core.pojo.response.ErrorResponseData;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.core.pojo.response.SuccessResponseData;
import cn.stylefeng.guns.goods.entity.Goods;
import cn.stylefeng.guns.goods.service.GoodsService;
import cn.stylefeng.guns.order.dto.OrderDTO;
import cn.stylefeng.guns.order.entity.Order;
import cn.stylefeng.guns.order.mapper.OrderMapper;
import cn.stylefeng.guns.order.service.OrderService;
import cn.stylefeng.guns.order.enums.OrderExceptionEnum;
import cn.stylefeng.guns.orderitem.entity.OrderItem;
import cn.stylefeng.guns.orderitem.service.OrderItemService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.List;

/**
 * order 服务实现类
 *
 * @author aria
 * @date 2021/02/20 20:24
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private GoodsService goodsService;

    //租用时间.默认一个月
    private static Integer borrowTime = 1;

    @Override
    public PageResult<Order> page(OrderDTO orderDTO) {

        // 构造条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();

        // 拼接查询条件-
        if (orderDTO != null && ObjectUtil.isNotEmpty(orderDTO.getOrderId())) {
            queryWrapper.like(Order::getOrderId, orderDTO.getOrderId());
        }

        // 拼接查询条件-
        if (orderDTO != null && ObjectUtil.isNotEmpty(orderDTO.getUserId())) {
            queryWrapper.like(Order::getUserId, orderDTO.getUserId());
        }
        PageResult<Order> orderPageResult = new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
        List<Order> rows = orderPageResult.getRows();
        for (int i = 0; i < rows.size(); i++) {
            Order order = rows.get(i);
            order.setItems(orderItemService.getItemsByOrderId(order));
        }
        // 查询分页结果
        return orderPageResult;
    }

    @Override
    public List<Order> list(OrderDTO orderDTO) {

        // 构造条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        List<Order> list = this.list(queryWrapper);
        //封装订单项
        for (int i = 0; i < list.size(); i++) {
            Order order = list.get(i);
            order.setItems(orderItemService.getItemsByOrderId(order));
        }

        return list;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ResponseData add(OrderDTO orderDTO) {
        // 将dto转为实体
        Order order = new Order();
        BeanUtil.copyProperties(orderDTO, order);
        //设置默认值
        //租用时间
        Calendar curr = Calendar.getInstance();
        order.setBorrowData(curr.getTime());
        //归还时间
        //给当前时间增加一周
        curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) + 7);
        order.setReturnData(curr.getTime());
        //添加订单,获取自增id
        this.baseMapper.insert(order);
        Integer orderId = order.getOrderId();
        //订单总价
        Double totalPrice = 0.0;
        //检查订单项
        List<OrderItem> paramItems = orderDTO.getItems();
        if (!ObjectUtil.isEmpty(paramItems)) {
            //构造订单项,并计算订单总价值
            for (OrderItem paramItem : paramItems) {
                if (paramItem.getItemNum() == null || paramItem.getItemNum() == 0.0) {
                    paramItem.setItemNum(1);
                }
                //获取商品
                Goods goods = goodsService.getBaseMapper().selectById(paramItem.getGoodsId());
                if (ObjectUtil.isEmpty(goods)) {
                    return new ErrorResponseData(500, "商品已下架,购买失败");
                }
                //检查库存
                //库存余额
                int newNum = goods.getGoodsCount() - paramItem.getItemNum();
                if (newNum < 0) {
                    return new ErrorResponseData(500, "商品名为: " + goods.getGoodsName() + " 的商品库存不足,请联系管理员补充库存");
                }
                //修改库存
                goods.setGoodsCount(newNum);
                goodsService.updateById(goods);

                QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("goods_id", goods.getGoodsId());
                //增加销量
                goods.setGoodsVolume(goods.getGoodsVolume() + 1);
                //更新商品信息
                goodsService.getBaseMapper().update(goods, queryWrapper);
                //如果传参为空,设置订单项内商品为数据库内的默认数据
                if (ObjectUtil.isEmpty(paramItem.getGoodsImage())) {
                    paramItem.setGoodsImage(goods.getGoodsImage());
                }
                if (ObjectUtil.isEmpty(paramItem.getGoodsName())) {
                    paramItem.setGoodsName(goods.getGoodsName());
                }
                if (ObjectUtil.isEmpty(paramItem.getDesc())) {
                    paramItem.setDesc(goods.getDesc());
                }
                if (paramItem.getGoodsPrice() == null || paramItem.getGoodsPrice() == 0.0) {
                    paramItem.setGoodsPrice(goods.getGoodsPrice());
                }
                //订单总价值增加
                if (paramItem.getGoodsPrice() == null || paramItem.getGoodsPrice() == 0.0) {
                    totalPrice += goods.getGoodsPrice() * paramItem.getItemNum();
                } else {
                    totalPrice += paramItem.getGoodsPrice() * paramItem.getItemNum();
                }

                //设置订单编号
                paramItem.setOrderId(orderId);
                orderItemService.getBaseMapper().insert(paramItem);
            }
        }
        //更新订单总价值
        order.setTotalPrice(totalPrice);
        //设置订单状态
        order.setStatus("0");
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        this.baseMapper.update(order, queryWrapper);
        return new SuccessResponseData();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(OrderDTO orderDTO) {
        this.removeById(orderDTO.getOrderId());
    }

    @Override
    public void edit(OrderDTO orderDTO) {

        // 根据id查询实体
        Order order = this.queryOrder(orderDTO);

        // 请求参数转化为实体
        BeanUtil.copyProperties(orderDTO, order);

        this.updateById(order);
    }

    @Override
    public Order detail(OrderDTO orderDTO) {
        Order order = this.queryOrder(orderDTO);
        order.setItems(orderItemService.getItemsByOrderId(order));
        return order;
    }

    @Override
    public Object listByUserId(OrderDTO orderDTO) {
        // 构造条件
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", orderDTO.getUserId()).orderByDesc("order_id");
        List<Order> list = this.list(queryWrapper);
        //封装订单项
        for (int i = 0; i < list.size(); i++) {
            Order order = list.get(i);
            order.setItems(orderItemService.getItemsByOrderId(order));
        }
        return list;
    }

    @Override
    public ResponseData pay(OrderDTO orderDTO) {
        Integer orderId = orderDTO.getOrderId();
        if (ObjectUtil.isEmpty(orderId)) {
            return new ErrorResponseData(400, "订单id不能为空");
        }
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Order> order_id = queryWrapper.eq("order_id", orderId);
        Order order = baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(order)) {
            return new ErrorResponseData(400, "订单不存在");
        }
        if ("1".equals(order.getStatus())) {
            return new ErrorResponseData(400, "已付款成功,请勿重复付款");
        }
        order.setStatus("1");
        QueryWrapper<Order> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("order_id", orderId);
        baseMapper.update(order, queryWrapper1);

        return new SuccessResponseData();
    }


    /**
     * 获取order
     *
     * @author aria
     * @since 2021/02/20 20:24
     */
    private Order queryOrder(OrderDTO orderDTO) {
        Order order = this.getById(orderDTO.getOrderId());
        if (ObjectUtil.isEmpty(order)) {
            throw new ServiceException(OrderExceptionEnum.NOT_EXISTED);
        }
        order.setItems(orderItemService.getItemsByOrderId(order));
        return order;
    }
}